<template>
  <div class="van-cell">
    <van-field
      readonly
      clickable
      :value="date"
      :label="label"
      :rules="rules"
      placeholder="选择日期"
      @click="show = true"
    />
    <van-calendar
      :max-range="maxRange"
      :default-date="defaultDate"
      :allow-same-day="true"
      :max-date="maxDate"
      v-model="show"
      v-bind="$attrs"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
export default {
  props:{
    value:{
      type:[String]
    },
    label:{
      type:String,
      default:'日历'
    },
    maxRange:{
      type:[String,Number],
      default:null
    },
    maxDate:{
      type:[Date]
    },
    rules:{
      type:[Array],
      default(){
        return []
      }
    },
    separator:{
      type:[String],
      default:'/'
    },
  },
  data() {
    return {
      date: '',
      show: false,
      defaultDate:'',
    };
  },
  watch:{
    value:{
      immediate:true,
      handler(v){
        if(v){
          this.defaultDate=this.createDate();
          this.date = v
        }else{
          this.defaultDate=null;
        }
      }
    }
  },
  methods: {
    createDate(){
      const createDate = s=>{
        const [year,month,day]=s.split(this.separator)
        return new Date(year,month-1,day)
      }
      return createDate(this.value||'')
    },
    formatDate(date) {
      return `${date.getFullYear()}${this.separator}${date.getMonth() + 1}${this.separator}${date.getDate()}`;
    },
    onConfirm(date) {
      this.show = false;
      this.date = `${this.formatDate(date)}`;
      this.$emit('input',this.date)
    },
  },
};
</script>

<style lang="less" scoped>
</style>